<?php
class User_Model_Auth extends Promotor_Model_Abstract {
	protected $_dbTableClass = 'User_Model_DbTable_User';
	
	// przyprawy dla hashowania kluczy
	const SALT_PASSWORD = "&ÞŚÓÐ&¿Ω⅛°ı±¿ð\ąśĸð¿)@#_";
	const SALT_KEY 		= ")!@(#*)(*#@)!(#*ºÞŚıÓÐ°¿¡⅛#_)#(################";

	/**
	 * Generowanie hasła
	 * @param string $username
	 * @param string $password
	 * @return string
	 */
	public static function saltPassword($username, $password) {
		return md5($username . self::SALT_PASSWORD . $password);
	}

	/**
	 * Generowanie klucza do aktywacji konta
	 * @param string $username
	 * @param string $password
	 * @return string
	 */
	static public function genKey($username, $password) {
		return md5($username . self::SALT_KEY . $password);
	}

	/**
	 * @param string $username
	 * @param string $password
	 * @return void
	 */
	public function login($username, $password) {
		$dbTable = $this->getDbTable();
		$db = $dbTable->getAdapter();
		
		$adapter = new Zend_Auth_Adapter_DbTable($db);
		$adapter->setTableName('user');
		$adapter->setIdentityColumn('email');
		$adapter->setCredentialColumn('password');
		$adapter->setCredentialTreatment("? AND registered = '1'");

		$adapter->setIdentity($username);
		$adapter->setCredential(self::saltPassword($username, $password));

		$auth = Zend_Auth::getInstance();
		
		try {
			$result = $auth->authenticate($adapter);
		} catch (Zend_Auth_Adapter_Exception $e) {
			$this->_setStatus(self::FAILURE);
			$this->_addException($e);
			return;
		}

		if ($result->getCode() === Zend_Auth_Result::SUCCESS) {
			$object = $adapter->getResultRowObject(null, array('password'));
			$auth->getStorage()->write($object);

			Zend_Session::regenerateId();

			$this->_setStatus(self::SUCCESS);
			return $result->getIdentity();
		} else {
			$this->_setStatus(self::FAILURE);
			$this->_addMessages($result->getMessages());
		}
	}
}